package com.macro.mall.demo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.macro.mall.common.api.CommonResult;

import com.macro.mall.demo.service.EsDocumentService;

import com.macro.mall.model.OrderInfo;
import com.macro.mall.model.PmsProduct;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;

import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class EsDocumentServiceImpl implements EsDocumentService {
    @Autowired
    private RestHighLevelClient client;




    /**
     * 查询
     */
    @Override
    public CommonResult<HashMap<String,Object>> selBoot(OrderInfo orderInfo) {
        HashMap<String, Object> HashList = new HashMap<>();
        List<Object> list = new ArrayList<>();

        try {
            if (orderInfo.getIndexName()==null){
                log.error("索引不能为空！！！");
            }
            SearchRequest searchRequest = new SearchRequest(orderInfo.getIndexName());
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            //搜索条件  getFieldName 搜索的字段  getName字段的内容
            boolQueryBuilder.must(QueryBuilders.matchQuery(orderInfo.getFieldName(),orderInfo.getName()));

            searchSourceBuilder.query(boolQueryBuilder);
            searchSourceBuilder.highlighter(new HighlightBuilder().field(orderInfo.getName())
                    .preTags("<span :style=\"color:"+orderInfo.getColor()+"\">").postTags("</span>"));
            //分页
            if (orderInfo.getPageSize()!=null && orderInfo.getPageNum()!=null){
                searchSourceBuilder.from((orderInfo.getPageNum()-1)*orderInfo.getPageSize());
                searchSourceBuilder.size(orderInfo.getPageSize());
            }
            // 排序
            if (orderInfo.getPrice()!=null){
                if (orderInfo.getOrderType().equals("DESC") || orderInfo.getOrderType().equals("desc")){
                    searchSourceBuilder.sort(orderInfo.getPrice(), SortOrder.DESC);
                }else {
                    if (orderInfo.getOrderType().equals("ASC") || orderInfo.getOrderType().equals("asc")){
                        searchSourceBuilder.sort(orderInfo.getPrice(), SortOrder.ASC);
                    }
                }
            }
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = searchResponse.getHits();
            SearchHit[] hits1 = hits.getHits();


            for (SearchHit hit : hits1) {
                String sourceAsString = hit.getSourceAsString();
                // 反序列化
                PmsProduct pmsProduct = JSONObject.parseObject(sourceAsString, PmsProduct.class);

                // 获取高亮字段
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields!=null){
                    HighlightField name = highlightFields.get(orderInfo.getName());
                    if (name!=null){
                        Text[] fragments = name.fragments();
                        String ste = "";
                        for (Text fragment : fragments) {
                            ste += fragment;
                        }
                        pmsProduct.setName(ste);

                    }
                }
                list.add(pmsProduct);
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        HashList.put(orderInfo.getIndexName(), list);
        return CommonResult.success(HashList);

    }

}
